package com.lgd.factoryattendance.Activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lgd.factoryattendance.Bean.AssemblyManagement;
import com.lgd.factoryattendance.Bean.K3cloudBom;
import com.lgd.factoryattendance.Bean.ProPPBom;
import com.lgd.factoryattendance.Bean.ProjectManagement;
import com.lgd.factoryattendance.Bean.ProjectSpinner;
import com.lgd.factoryattendance.Bean.ProjectType;
import com.lgd.factoryattendance.R;
import com.lgd.factoryattendance.Utils.ScreenUtils;
import com.lgd.factoryattendance.Utils.ToastUtils;
import com.lgd.factoryattendance.View.LoaringDialog;
import com.lgd.factoryattendance.adapter.AssemblyNameAdapter;
import com.lgd.factoryattendance.adapter.BomListAdapter;
import com.lgd.factoryattendance.adapter.MyAdapter;
import com.lgd.factoryattendance.databinding.ActivityBomListInfoBinding;
import com.lgd.factoryattendance.databinding.BomListPopBinding;
import com.lgd.factoryattendance.httpService.API;
import com.lgd.factoryattendance.httpService.httpPort.IResponse;
import com.lgd.factoryattendance.httpService.httpPort.IStringResponse;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

public class BomListInfoActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "BomListInfoActivity";
    private ActivityBomListInfoBinding bomBinding;
    private final List<ProjectSpinner> projectnameList = new ArrayList<>();  // 项目 列表
    MyAdapter adapter;
    String ANDROID_ID;
//    LoaringDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bomBinding = ActivityBomListInfoBinding.inflate(getLayoutInflater());

        setContentView(bomBinding.getRoot());
//        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        bomInit();
    }

    @SuppressLint("HardwareIds")
    public void bomInit(){
//        loadingDialog = LoaringDialog.getInstance(this);
        ANDROID_ID = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
        bomBinding.layoutBack.setOnClickListener(this);
        bomBinding.ivRefresh.setOnClickListener(this);
        projectType();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.layout_back:
                finish();
                break;
            case R.id.iv_refresh:
                reStartActivity();
                break;
            default:
                break;
        }
    }

    // 获取 项目分类 数据
    public List<String> projectType_list = new ArrayList<>();
    public void projectType(){
        API.projectType(new IResponse() {
            @Override
            public void onSuccess(String response) throws IOException {
                BomListInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(response);
                        List<ProjectType> projectTypeList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectType>>(){}.getType());
                        Log.d(TAG, "-----项目类型----"+projectTypeList);
                        if (projectTypeList.size() > 0){
                            projectType_list.add("选择类型");
                            for (ProjectType type : projectTypeList) {
                                projectType_list.add(type.getTypename());
                            }
                        }
                        typeSpinner();
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {
                Log.d(TAG, "onFail: -----刷新错误------:  "+statusCode);
            }
        });
    }

    ArrayAdapter<String> typeSpinner_adapter;
    //  类型 spinner 实例化
    public void typeSpinner(){
        typeSpinner_adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.spinner_item, projectType_list);
        bomBinding.spProjectType.setAdapter(typeSpinner_adapter);
        bomBinding.spProjectType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                Log.d(TAG, "----spinner选中类型----"+projectType_list.get(position));
                String str_spinner = projectType_list.get(position);
                projectnameList.clear();
                adapter = new MyAdapter(projectnameList, BomListInfoActivity.this);
                bomBinding.projectUnitSP.setAdapter(adapter);
                if (str_spinner.equals("选择类型")) {
                    ToastUtils.warnShowLong(getApplicationContext(),"请选择项目类型！！！");
                    bomBinding.ivImg.setVisibility(View.VISIBLE);
                }else {
                    bomBinding.ivImg.setVisibility(View.GONE);
                    ProjectType projectType = new ProjectType();
                    projectType.setTypename(projectType_list.get(position));
                    projectType.setSerialnumber(ANDROID_ID);
                    getStartProjectInfo(projectType);
                }
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }

    public void getStartProjectInfo(ProjectType projectType){
        API.getStartProjectInfo(projectType, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                BomListInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<ProjectManagement> projectManagementList = new Gson().fromJson(j.getString("data"), new TypeToken<List<ProjectManagement>>(){}.getType());

                        // 清洗数据 null 值
                        Iterator<ProjectManagement> iterator = projectManagementList.iterator();
                        while (iterator.hasNext()) {
                            ProjectManagement item = iterator.next();
                            if (item.getMaterialListNumber() == null) {
                                iterator.remove();
                            }
                        }

                        projectnameList.clear();
                        if (projectManagementList.size() > 0){
                            for (ProjectManagement p : projectManagementList) {
                                projectnameList.add(new ProjectSpinner(p.getProjectname(),
                                        p.getProductacode(),
                                        p.getProjectid(),
                                        p.getDeptid()));
                            }
                        }else {
                            ToastUtils.warnShowLong(getApplicationContext(),"当前设备下没有该类型的项目，请重新选择");
                            setAssemblyAdapter(null);
                        }
                        setProject(projectnameList);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    public void setProject(List<ProjectSpinner> projectnameList){
        adapter = new MyAdapter(projectnameList, BomListInfoActivity.this);
        bomBinding.projectUnitSP.setAdapter(adapter);
        bomBinding.projectUnitSP.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                Log.d(TAG, "---项目名称---"+projectnameList.get(position).getProjectName()+
                        "--项目code---"+projectnameList.get(position).getProjectACode()+
                        "---项目 id---"+projectnameList.get(position).getProjectId()+
                        "---部门id--"+projectnameList.get(position).getDeptId());

                K3cloudBom k3cloudBom = new K3cloudBom();
                k3cloudBom.setProductacode(projectnameList.get(position).getProjectACode());
                getAssemblyListByCode(k3cloudBom);
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {}
        });
    }
    // 获取 金蝶系统部装列表
    public void getAssemblyListByCode(K3cloudBom k3cloudBom){
        API.getAssemblyListByCode(k3cloudBom, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                BomListInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
                        List<K3cloudBom> k3cloudBomList = new Gson().fromJson(j.getString("data"), new TypeToken<List<K3cloudBom>>(){}.getType());
                        System.out.println("---k33333333333----"+ k3cloudBomList);
                        setAssemblyAdapter(k3cloudBomList);
                        if (k3cloudBomList.isEmpty()){
                            bomBinding.ivImg.setVisibility(View.VISIBLE);
                        }else {
                            bomBinding.ivImg.setVisibility(View.GONE);
                        }
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }
    // 设置金蝶部装 适配器
    public void setAssemblyAdapter(List<K3cloudBom> k3cloudBomList){
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
        bomBinding.rvAssemblyName.setLayoutManager(gridLayoutManager);
        AssemblyNameAdapter assemblyNameAdapter = new AssemblyNameAdapter(this,k3cloudBomList);
        bomBinding.rvAssemblyName.setAdapter(assemblyNameAdapter);
        assemblyNameAdapter.setMonRecyclerItemClickListener(new AssemblyNameAdapter.onRecyclerItemClickListener() {
            @Override
            public void onRecyclerItemClick(int position) {
                System.out.println("----点击了第"+(position+1)+"个部装----");
                System.out.println("----部装名称---" + k3cloudBomList.get(position).getAssemblyName() +
                        "----部装id---" + k3cloudBomList.get(position).getProjectId());

                K3cloudBom k3cloudBom = new K3cloudBom();
                k3cloudBom.setProjectId(k3cloudBomList.get(position).getProjectId());
                k3cloudBom.setAssemblyName(k3cloudBomList.get(position).getAssemblyName());
                k3cloudBom.setProductacode(k3cloudBomList.get(position).getProductacode());
                getBomListByCodeAndAssembly(k3cloudBom,
                                            k3cloudBomList.get(position).getAssemblyName(),
                                            k3cloudBomList.get(position).getProductacode());
            }
        });
    }

    // bom 清单
    public void getBomListByCodeAndAssembly(K3cloudBom k3cloudBom, String assemblyName, String productacode){
        API.getBomListByCodeAndAssembly(k3cloudBom, new IStringResponse() {
            @Override
            public void onSuccess(String result) {
                BomListInfoActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        JSONObject j = JSONObject.parseObject(result);
//                        System.out.println("---bom清单原始数据----"+ result);
                        List<ProPPBom> proPPBomList = new Gson().fromJson(j.getString("data"),  new TypeToken<List<ProPPBom>>(){}.getType());
                        System.out.println(proPPBomList.size() + "---bom清单----"+ proPPBomList);
                        setBomPop(proPPBomList, assemblyName, productacode);
                    }
                });
            }
            @Override
            public void onFail(int statusCode) {}
        });
    }

    //  BOM 清单详情 弹窗
    PopupWindow bom_pop;
    BomListPopBinding bomPopBinding;
    @SuppressLint("SetTextI18n")
    public void setBomPop(List<ProPPBom> proPPBomList, String assemblyName, String productacode) {
        setAlpha(0.5f);
        bomPopBinding = BomListPopBinding.inflate(getLayoutInflater());
        View bom_list_view = bomPopBinding.getRoot();
        int width = ScreenUtils.getWidth(getApplicationContext());
        int height = ScreenUtils.getHeight(getApplicationContext());
        bom_pop = new PopupWindow
                (bom_list_view, width * 19/20, height * 12/13);
        bom_pop.setTouchable(true);
        bom_pop.setFocusable(true);
        bom_pop.setOutsideTouchable(true);
        bom_pop.setBackgroundDrawable(new ColorDrawable(0x0000));
        bom_pop.showAtLocation(BomListInfoActivity.this.getWindow().getDecorView(), Gravity.CENTER,0,0);
        bomPopBinding.tvBomTitle.setText("("+ productacode + "—" +assemblyName + ") 用料清单"); //  bom 标题
        setBomData(proPPBomList);
    }

    // 设置 BOM 弹窗数据
    public void setBomData(List<ProPPBom> proPPBomList) {
        bom_pop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setAlpha(1f);
            }
        });
        bomPopBinding.ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bom_pop.dismiss();
            }
        });
        bomPopBinding.bomListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                选中的 列表
//                System.out.println("----点击了第"+(position)+"个bom清单----");
//                bomPopBinding.bomListview.setBackground();
            }
        });

        if (proPPBomList.size() == 0){
            bomPopBinding.tvFinishBom.setVisibility(View.VISIBLE);
        }else {
            bomPopBinding.tvFinishBom.setVisibility(View.GONE);
        }
        // bom 清单数据适配器
        BomListAdapter bomListAdapter = new BomListAdapter(this, proPPBomList);
        bomPopBinding.bomListview.setAdapter(bomListAdapter);
    }

    //  弹窗遮罩层
    private void setAlpha(float f) {
        WindowManager.LayoutParams lp =getWindow().getAttributes();
        lp.alpha = f;
        getWindow().setAttributes(lp);
    }

    //     重启当前页面
    private void reStartActivity() {
        Intent intent = getIntent();
        overridePendingTransition(0, 0);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        finish();
        overridePendingTransition(0, 0);
        startActivity(intent);
    }

//    隐藏导航栏
//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        super.onWindowFocusChanged(hasFocus);
//        if (hasFocus) {
//            // 沉浸式模式增强
//            View decorView = getWindow().getDecorView();
//            int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN
//                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
//                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
//            decorView.setSystemUiVisibility(uiOptions);
//        }
//    }



}